package com.zhentao.map.controller;

import com.zhentao.util.ResultVo;
import com.zhentao.map.service.MapDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 设备控制器
 * 提供设备相关的API接口
 */
@RestController
@RequestMapping("/device")
@CrossOrigin(origins = "*")
public class MapDeviceController {

    @Autowired
    private MapDeviceService mapDeviceService;

    /**
     * 获取设备最新水质数据（从Redis）
     * @param deviceId 设备ID
     * @return 最新水质数据
     */
    @GetMapping("/latest")
    @SuppressWarnings("unchecked")
    public ResultVo<Map<String, Object>> getLatestWaterQualityData(@RequestParam String deviceId) {
        try {
            Map<String, Object> latestData = mapDeviceService.getLatestWaterQualityDataFromRedis(deviceId);
            if (latestData != null && !latestData.isEmpty()) {
                return ResultVo.success(latestData);
            } else {
                return ResultVo.error(404, "未找到设备数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "获取数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有设备列表
     * @return 设备列表
     */
    @GetMapping("/list")
    @SuppressWarnings("unchecked")
    public ResultVo<List<Map<String, Object>>> getDeviceList() {
        try {
            return ResultVo.success(mapDeviceService.getDeviceList());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "获取设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备详细信息
     * @param deviceId 设备ID
     * @return 设备详细信息
     */
    @GetMapping("/info")
    @SuppressWarnings("unchecked")
    public ResultVo<Map<String, Object>> getDeviceInfo(@RequestParam String deviceId) {
        try {
            return ResultVo.success(mapDeviceService.getDeviceInfo(deviceId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(500, "获取设备信息失败: " + e.getMessage());
        }
    }
}
